package com.xiaoshou.dao;

import java.io.File;
import java.io.IOException;
import java.util.List;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.cn.smart.SmartChineseAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.FieldType;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.IndexWriterConfig.OpenMode;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.store.LockObtainFailedException;
import org.apache.lucene.util.Version;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.springframework.stereotype.Repository;

import com.xiaoshou.pojo.Question;

@Repository
public class IndexFile extends BaseDao<Question, String> {

	public final static String indexDirForQuestion = "F:\\工作相关索引\\销售索引";

	/**
	 * 更新索引(修改问题),先删除修改前的'问题'，再更新修改后的。
	 * @param question
	 */
	public void updateIndexFileForQuestionByUpdate(IndexSearcher searcher, Question q){
		
		Analyzer sa = new SmartChineseAnalyzer(Version.LUCENE_40);
		IndexWriterConfig iwc = new IndexWriterConfig(Version.LUCENE_40, sa);
		iwc.setOpenMode(OpenMode.APPEND);
		try {
			Directory dir1 = FSDirectory.open(new File(indexDirForQuestion));
			IndexWriter writer = new IndexWriter(dir1, iwc);
			writer.deleteDocuments(new Term("id"));
			writer.close();
		} catch (CorruptIndexException e) {
			e.printStackTrace();
		} catch (LockObtainFailedException e) {
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	/**
	 * 根据问题的单一ID,删除单条索引，
	 * @param questionId
	 */
	public void deleteOneIndexInIndexById(String questionId){
		IndexWriter writer = null;
		Analyzer sa = new SmartChineseAnalyzer(Version.LUCENE_40);
		IndexWriterConfig iwc = new IndexWriterConfig(Version.LUCENE_40, sa);
		Directory dir1 = null;
		try {
			dir1 = FSDirectory.open(new File(indexDirForQuestion));
			writer = new IndexWriter(dir1, iwc);
			Term term = new Term("id", questionId);
			System.out.println(questionId+"\t的索引被删");
			writer.deleteDocuments(term);
			writer.commit();
			writer.close();
			
		} catch (CorruptIndexException e) {
			e.printStackTrace();
		} catch (LockObtainFailedException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally{
			try {
				if(writer!=null){
					writer.close();
				}
			} catch (CorruptIndexException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	/**
	 * 往索引中添加新纪录,更新索引(添加新的问题，存入索引)
	 * @param q
	 */
	public void updateIndexFileForQuestion(Question q) {
		Analyzer sa = new SmartChineseAnalyzer(Version.LUCENE_40);
		IndexWriterConfig iwc = new IndexWriterConfig(Version.LUCENE_40, sa);
		iwc.setOpenMode(OpenMode.APPEND);
		IndexWriter writer = null;
		try {
			Directory dir1 = FSDirectory.open(new File(indexDirForQuestion));
			writer = new IndexWriter(dir1, iwc);

			FieldType ft = new FieldType();
			ft.setIndexed(true);
			ft.setStored(true);
			ft.setTokenized(true);
			
			FieldType ft2 = new FieldType();
			
			//ft2.setNumericType(NumericType.INT);
			ft2.setIndexed(true);
			ft2.setStored(true);
			ft2.setTokenized(false);

			Document doc = new Document();
			doc.add(new Field("id", q.getId(), ft2));
			doc.add(new Field("questionname", q.getQuestionname(), ft));
			writer.addDocument(doc);
			writer.close();
		} catch (CorruptIndexException e) {
			e.printStackTrace();
		} catch (LockObtainFailedException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally{
			try {
				if(writer!=null){
					writer.close();
				}
				if(sa!=null){
					sa.close();
				}
			} catch (CorruptIndexException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
	}

	/**
	 * 创建索引
	 * @param indexDir
	 * @return
	 * @throws IOException
	 */
	public int indexFileForQuestion() {
		Analyzer sa = new SmartChineseAnalyzer(Version.LUCENE_40);
		IndexWriterConfig iwc = new IndexWriterConfig(Version.LUCENE_40, sa);
		iwc.setOpenMode(OpenMode.CREATE);

		try {
			Directory dir1 = FSDirectory.open(new File(indexDirForQuestion));
			IndexWriter writer = new IndexWriter(dir1, iwc);
			@SuppressWarnings("unused")
			int numIndexed = -1;
			try {
				FieldType ft = new FieldType();
				ft.setIndexed(true);
				ft.setStored(true);
				ft.setTokenized(true);

				FieldType ft2 = new FieldType();
				ft2.setIndexed(true);
				ft2.setStored(true);
				ft2.setTokenized(false);

				String hql = "from Question";
				Query query = getSessionOpen().createQuery(hql);
				@SuppressWarnings("unchecked")
				List<Question> questionsList = (List<Question>) query.list();
				Question[] questionsArray = (Question[]) questionsList
						.toArray(new Question[questionsList.size()]);
				for (int i = 0; i < questionsArray.length; i++) {
					Document doc = new Document();
					//doc.add(new Field("id", String.valueOf(questionsArray[i].getId()), ft2));
					//doc.add(new Field("questionname", String.valueOf(questionsArray[i].getQuestionname()), ft));
					doc.add(new Field("id", String.valueOf(questionsArray[i].getId()), ft2));
					doc.add(new Field("questionname", String.valueOf(questionsArray[i].getQuestionname()), ft));
					writer.addDocument(doc);
				}
				numIndexed = writer.maxDoc();
				
				writer.close();
				sa.close();
			} finally {
				writer.close();
				//sa.close();
			}
		} catch (CorruptIndexException e) {
			e.printStackTrace();
		} catch (LockObtainFailedException e) {
			e.printStackTrace();
		} catch (HibernateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return 0;
	}

}
